package algorithmExample.BinarySearch;

import java.util.Arrays;

/**
 * @Author: zhangrongqing
 * @Date: 2019/11/9 16:13
 */
//假设按照升序排序的数组在预先未知的某个点上进行了旋转。
//
//        ( 例如，数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
//
//        搜索一个给定的目标值，如果数组中存在这个目标值，则返回它的索引，否则返回 -1 。
//
//        你可以假设数组中不存在重复的元素。
//
//        你的算法时间复杂度必须是 O(log n) 级别。
//
//        示例 1:
//
//        输入: nums = [4,5,6,7,0,1,2], target = 0
//        输出: 4
//        示例 2:
//
//        输入: nums = [4,5,6,7,0,1,2], target = 3
//        输出: -1
public class SearchInRotatedSortedArray {

    public int search(int[] nums, int target) {
        int k = nums.length - 1;
        int[] searchArray;
        int result = -1;
        if (nums[k / 2] == target) {
            return k / 2;
        }
        if (k == 0) {
            return -1;
        }
        if (nums[k / 2] > target && nums[k / 2 + 1] >= target) {
            searchArray = Arrays.copyOfRange(nums, 0, k / 2 - 1);
            result = search(searchArray, target);
        } else {
            searchArray = Arrays.copyOfRange(nums, k / 2 + 1, nums.length);
            result = search(searchArray, target) + k / 2 + 1;
        }
        return result;
    }

    public int find_rotation_index(int[] num) {
        int right = 0, left = num.length;
        while (right <= left) {
            int pos = (right + left) / 2;
            if (num[pos] > num[pos + 1]) {
                return pos + 1;
            }
            if (num[right] > num[pos]) {
                left = pos - 1;
            } else {
                right = pos + 1;
            }
        }
        return 0;
    }

    public static void main(String[] args) {
//        int[] input = new int[]{0,1,2,4,5,6,7};
//        int target = 1;
//        int result = new SearchInRotatedSortedArray().search(input,target);
//        System.out.printf("target position is "+ result);

        int[] input = new int[]{4, 5, 6, 7, 0, 1, 2};
        int target = 1;
        int result = new SearchInRotatedSortedArray().find_rotation_index(input);
        System.out.printf("target position is " + result);
    }
}
